using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using WindowsPhoneGame1.LevelItems;

namespace WindowsPhoneGame1.Collisions
{
    public class CollisionManager
    {
        private Level level;
        private List<Collision> collisions;

        private CollisionHandler[] collisionHandlers;

        public CollisionManager(Level level)
        {
            // TODO: Construct any child components here
            this.level = level;
            collisions = new List<Collision>();

            collisionHandlers = new CollisionHandler[3];
            collisionHandlers[0] = new ChassisOnTrackCollisionhandler(level);
            collisionHandlers[1] = new WheelOnTrackCollisionhandler(level);
            collisionHandlers[2] = new OnCoinCollisionhandler(level);
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            LevelItem[] levelItems = level.GetTrackItems();
            Car car = level.GetCar();

            for (int i = 0; i < levelItems.Length - 1; i++)
            {
                Collision c = levelItems[i].CollidesWith(car);

                if (c.GetContainmentType() != ContainmentType.Disjoint)
                    collisions.Add(c);

                c = levelItems[i].CollidesWith(car.GetRearWheel());

                if (c.GetContainmentType() != ContainmentType.Disjoint)
                    collisions.Add(c);

                c = levelItems[i].CollidesWith(car.GetFrontWheel());

                if (c.GetContainmentType() != ContainmentType.Disjoint)
                    collisions.Add(c);
            }

            collisions.Sort();

            while (collisions.Count > 0)
            {
                Collision c = collisions.First();
                collisions.RemoveAt(0);

                foreach (CollisionHandler handler in collisionHandlers)
                    if (handler.CollisionType == c.CollisionType)
                    {
                        handler.HandleCollision(c);
                        break;
                    }
            }
        }
    }
}
